import { createGlobalState } from "@vueuse/core"
import { uniqBy } from "lodash-es"
import { ref } from "vue"

export const useTypePopver = createGlobalState(() => {
  const visible = ref(false)
  const input = ref("")
  const isFocused = ref(false)
  let currentImageAnnotationRef: any
  const listData = ref<any[]>([])

  function transformData(data: any[]) {
    const newData = data.map((item) => {
      const name = item.normCoords.split(" ")[0]
      return {
        name,
        color: item.stroke,
        normCoords: item.normCoords
      }
    })
    return newData
  }

  function setListData(data: any[]) {
    return transformData(data)
  }

  function setInputData(name: string) {
    input.value = name
  }

  function show(ImageAnnotationRef: any) {
    currentImageAnnotationRef = ImageAnnotationRef
    const data = ImageAnnotationRef.getRectData()
    const activeData = currentImageAnnotationRef.getActiveObject()
    if (activeData) {
      const normCoordsArr = activeData.normCoords.split(" ")
      const name = normCoordsArr[0]
      setInputData(name)
    }
    const filterData = uniqBy(data, "stroke").filter((item: any) => {
      return item.fill === "transparent"
    })
    listData.value = setListData(filterData)
    // setInputData(listData.value[listData.value.length - 1].name)
    visible.value = true
  }
  function hide() {
    visible.value = false
  }
  const updateText = () => {
    currentImageAnnotationRef.setGlobalText(input.value)
    currentImageAnnotationRef.setActiveObjectName(input.value)
    const data = currentImageAnnotationRef.getRectData()
    const filterData = uniqBy(data, "stroke").filter((item: any) => {
      return item.fill === "transparent"
    })
    listData.value = setListData(filterData)

  }
  const getSelectName = (name: string) => {
    return name === input.value
  }
  const handleClickItem = (item: any) => {
    currentImageAnnotationRef.setActiveObjectByName(item.name)
    currentImageAnnotationRef.setGlobalText(item.name)
    input.value = item.name
  }
  const deleteItem = () => {
    console.log(input.value, "itemitem")
    currentImageAnnotationRef.deleteMultiRect(input.value)
    listData.value = listData.value.filter((item) => {
      return item.name !== input.value
    })
    if(listData.value.length === 0){
      input.value = ""
      currentImageAnnotationRef.handleClearDark()
    }
  }
  return {
    visible,
    handleClickItem,
    listData,
    input,
    isFocused,
    getSelectName,
    show,
    updateText,
    deleteItem,
    hide
  }
})
